import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/base/base_function.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

//控制器
class PayPasswordCheckController extends BaseController {
  final PayNumKeyboardController _textEditingController = PayNumKeyboardController('');
  final _resultData = ''.obs;

  ///验证是否成功
  bool success = false;

  ///密码验证
  Future<bool> checkPassword(String password) {
    Tools.showLoading();
    return Network.validatePayPassword(password).then((value) {
      Tools.hideLoading();
      success = value;
      return success;
    }).catchError((onError) {
      Tools.hideLoading();
      return false;
    });
  }
}

class PasswordCheckPopup extends StatelessWidget {
  ///回调
  final CallbackPayPassword callback;

  PasswordCheckPopup({super.key, required this.callback});

  final PayPasswordCheckController controller = PayPasswordCheckController();

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 375.w,
      decoration: BoxDecoration(
        color: Tools.fromHex("#F8F8F8"),
        borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部：关闭按钮和标题
          Container(
            margin: const EdgeInsets.only(top: 20),
            padding: EdgeInsets.only(left: 10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                BaseInteractive(
                  onClick: () {
                    Get.back();
                  },
                  childWidget: const Icon(Icons.close),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      "输入支付密码",
                      style: setTextStyle(15, FontWeight.w500, Tools.fromHex("#333333")),
                    ),
                  ),
                ),
                SizedBox(width: 10.w)
              ],
            ),
          ),
          SizedBox(height: 15.w),

          // 中间部分：密码输入框
          Flexible(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Obx(() {
                    return _buildNumberWidget(controller._resultData.value.length);
                  }),
                ],
              ),
            ),
          ),

          // 底部：键盘部分
          Container(
            child: PayNumKeyboard(
              controller: controller._textEditingController,
              onChanged: (value) async {
                controller._resultData.value = value;
                if (value.length == 6) {
                  bool res = await controller.checkPassword(value);
                  callback(res);
                  if (res == true) {
                    Tools.showToast("验证成功");
                    Get.back();
                  } else {
                    Tools.showToast("密码错误,请重新输入");
                  }
                  controller._textEditingController.clearText();
                  controller._resultData.value = '';
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  // 密码输入框部分
  Widget _buildNumberWidget(int length) {
    return SizedBox(
      height: 47.w,
      width: 282.w,
      child: ListView.builder(
        padding: EdgeInsets.zero,
        scrollDirection: Axis.horizontal,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: 6,
        itemExtent: 47,
        itemBuilder: (BuildContext context, int index) {
          bool showPoint = index < length;
          return _buildNumberItemWidget(index, showPoint);
        },
      ),
    );
  }

  // 密码输入框的每个格子
  Widget _buildNumberItemWidget(int index, bool showPoint) {
    BorderRadiusGeometry borderRadius = const BorderRadius.only();
    Color color = Colors.black12;
    BorderSide borderSide0 = BorderSide(width: 0.w, color: color);
    BorderSide borderSide05 = BorderSide(width: 0.5.w, color: color);
    BoxBorder border = Border(top: borderSide05, left: borderSide05, bottom: borderSide05, right: borderSide0);
    return Container(
      height: 47.w,
      width: 47.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: borderRadius,
        border: border,
      ),
      child: showPoint
          ? Container(
              height: 10.w,
              width: 10.w,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(5.w),
              ),
            )
          : Container(),
    );
  }
}

// 键盘部分
class PayNumKeyboard extends StatelessWidget {
  final PayNumKeyboardController controller;
  final ValueChanged<String> onChanged;

  PayNumKeyboard({required this.controller, required this.onChanged, Key? key}) : super(key: key);

  static const List<PayKeyboardDataBean> _keyboardDataList = [
    PayKeyboardDataBean(PayKeyboardType.num, "1"),
    PayKeyboardDataBean(PayKeyboardType.num, "2"),
    PayKeyboardDataBean(PayKeyboardType.num, "3"),
    PayKeyboardDataBean(PayKeyboardType.num, "4"),
    PayKeyboardDataBean(PayKeyboardType.num, "5"),
    PayKeyboardDataBean(PayKeyboardType.num, "6"),
    PayKeyboardDataBean(PayKeyboardType.num, "7"),
    PayKeyboardDataBean(PayKeyboardType.num, "8"),
    PayKeyboardDataBean(PayKeyboardType.num, "9"),
    PayKeyboardDataBean(PayKeyboardType.none, ""),
    PayKeyboardDataBean(PayKeyboardType.num, "0"),
    PayKeyboardDataBean(PayKeyboardType.delete, ""),
  ];

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: (125 / 54),
      ),
      itemBuilder: (context, index) {
        return buildNumKeyboardItem(_keyboardDataList[index]);
      },
      itemCount: _keyboardDataList.length,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
    );
  }

  Widget buildNumKeyboardItem(PayKeyboardDataBean keyboardDataBean) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (keyboardDataBean.type == PayKeyboardType.delete) {
          if (controller.value.isNotEmpty) {
            controller.value = controller.value.substring(0, controller.value.length - 1);
            onChanged(controller.value);
          }
        } else if (keyboardDataBean.type == PayKeyboardType.num) {
          controller.value += keyboardDataBean.value;
          onChanged(controller.value);
        }
      },
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: keyboardDataBean.type == PayKeyboardType.num ? Colors.transparent : Colors.black12,
          border: Border(
            top: BorderSide(width: 0.5.w, color: Colors.black12),
            right: BorderSide(width: 0.5.w, color: Colors.black12),
          ),
        ),
        child: keyboardDataBean.type == PayKeyboardType.delete
            ? const Icon(Icons.backspace_outlined)
            : Text(
                keyboardDataBean.value,
                style: const TextStyle(
                  fontSize: 20,
                  color: Colors.black,
                ),
              ),
      ),
    );
  }
}

enum PayKeyboardType {
  none,
  num,
  delete,
}

class PayKeyboardDataBean {
  final PayKeyboardType type;
  final String value;

  const PayKeyboardDataBean(this.type, this.value);
}

class PayNumKeyboardController extends RxString {
  PayNumKeyboardController(super.initial);

  void setText(String text) {
    value = text;
  }

  void clearText() {
    value = '';
  }
}

///唤起输入密码弹窗
void showPasswordCheckPopup(CallbackPayPassword callback) {
  showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) {
        return PasswordCheckPopup(callback: callback);
      });
}
